// pagesEnterprise/pages/enterpriseAuthentication/enterpriseAuthentication.js
import ajax from '../../../utils/index'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    companyId: '',
    type: 1, //1认领 2编辑 
    positionIndex: 0,
    positionArr: ['法人', '股东', '高管', '人事', '行政', '普通员工'],
    form: {
      "businessLicense": "", //营业执照 --
      "companyPicture": "", //企业照片 --
      "companyProfile": "", //企业介绍 --
      "enterpriseName": "", //企业名称 --
      "businessCard": "", //名片上传 --
      "industryInvolved": "", //所属行业 **
      "site": "", //详情地址 **
      "post": "", //职位
      // "sign": 0, //审核 0 已提交 1通过 2拒绝
      "wxName": "", //微信姓名 --
      "wxNumber": "", //微信号 --
      "wxPhone": "", //微信手机号
      "wxPortrait": "", //微信头像
      "wxUserId": "", //微信用户id
    },
    detail: '',
    // 文件上传数组
    honorCertificationArr: [],
    agreement: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options-------------', options)
    const { type, id, companyId, companyName } = options
    if (options && type == '3' && companyId && companyName) this.get_companyinfo_claim(companyId, companyName);
    if (options && type == '2') {
      wx.setNavigationBarTitle({ title: '企业信息修改' })
      this.setData({ type: type, companyId: id })
      this.get_company_info()
    }
    const userInfo = wx.getStorageSync('userInfo')
    console.log('userInfo', userInfo)
    // const userInfo = app.globalData.userInfo
    // console.log(userInfo)
    this.setData({
      ['form.wxUserId']: userInfo.id,
      ['form.wxPhone']: userInfo.wxPhone,
      ['form.wxPortrait']: userInfo.headimgUrl,
    })
  },
  /**
   * 协议事件
   */
  agreementChange(event) {
    this.data.agreement = event.detail
  },
  async get_companyinfo_claim(companyId, companyName) {
    const res = await ajax.get('/wx/appletCompanyData/companyinfoClaim', { companyId, companyName })
    const form = res.data;
    const formData = this.data.form;
    //企业名称 --
    formData.enterpriseName = form.companyName || ''
    //企业名称 --
    formData.company = form.companyName || ''
    //所属行业 **
    formData.industryInvolved = form.industryInvolved || ''
    //详情地址 **
    formData.site = form.businessAddress || ''
    //企业照片 --
    formData.companyPicture = form.companyLogo || ''
    this.setData({ form: formData, type: 3 })
  },
  /**
   * 获取企业信息
   */
  get_company_info: function () {
    let that = this
    ajax.get('/wx/appletCorporateHome/info', {
      id: that.data.companyId,
      wxUserid: app.globalData.userInfo.id
    }).then(res => {
      if (res.code == 200) {
        let form = res.data
        that.setData({
          form: form,
          honorCertificationArr: res.data.honorCertification ? res.data.honorCertification.split(',') : []
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },

  /**
   * 搜索关键词改变
   */
  searchTextChange: function (e) {
    this.setData({
      ['form.enterpriseName']: e.detail.value
    })
  },

  /**
   * 搜索企业
   */
  search: function () {
    let that = this
    let text = this.data.form.enterpriseName
    if (!text) {
      wx.showToast({
        title: '请输入完整企业名称',
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '搜索中',
    })
    ajax.get('/wx/appletCompanyData/selectData',{
      companyName: text
    }).then(res => {
      if (res.code == 200 && res.data.status == '200') {
        that.setData({
          ['form.enterpriseName']: res.data.companyName,
          ['form.industryInvolved']: res.data.industryInvolved,
          ['form.site']: res.data.annalsSite,
        })
        setTimeout(() => {
          wx.hideLoading()
        }, 1500)
        wx.showToast({
          title: '搜索成功，已填入企业信息',
          icon: 'none'
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: res.data.message || res.msg,
          icon: 'none'
        })
      }
    })
  },

  /**
   * 表单提交
   */
  submit: function (e) {
    let that = this
    // console.log('表单', e.detail.value)
    // console.log('form', this.data.form)

    let form = this.data.form

    if (that.data.type == 2) { //编辑
      form.ambitus = e.detail.value.ambitus
      console.log(form)

      //跳转预览页面
      return wx.navigateTo({
        url: '/pagesEnterprise/pages/enterprisePreview/enterprisePreview?type=' + that.data.type,
        success: function (res) {
          res.eventChannel.emit('companyFormData', { data: form })
        }
      })
    }
    if (!this.data.agreement) return wx.showToast({
      title: '请同意并阅读盈联易单配服务协议',
      icon: 'none'
    })
    //添加
    const userInfo = wx.getStorageSync('userInfo')
    form.wxUserId = userInfo.id
    form.companyProfile = e.detail.value.companyProfile
    form.wxName = e.detail.value.wxName
    form.wxPhone = e.detail.value.wxPhone
    form.post = that.data.positionArr[that.data.positionIndex]

    console.log('表单合并', form)

    //表单验证
    let result = this.rules()
    console.log(result)
    if (!result.status) {
      wx.showToast({
        title: result.value,
        icon: 'none'
      })
      return
    }
    //跳转预览页面
    return wx.navigateTo({
      url: '/pagesEnterprise/pages/enterprisePreview/enterprisePreview?type=' + that.data.type,
      success: function (res) {
        res.eventChannel.emit('companyFormData', { data: form })
      }
    })
    
  },

  /**
   * 路由 - 预览
   */
  previewCompany: function () {
    //表单验证
    let result = this.rules()
    console.log(result)
    if (!result.status) {
      wx.showToast({
        title: result.value,
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: '/pages/park/company/edit/preview',
    })
  },

  /**
   * 表单验证
   */
  rules: function (callback) {
    let form = this.data.form
    if (!form.enterpriseName) {
      return {
        status: false,
        value: '请输入企业名称'
      }
    }
    if (!form.companyPicture) {
      return {
        status: false,
        value: '请上传企业照片'
      }
    }
    if (!form.companyProfile) {
      return {
        status: false,
        value: '请输入企业介绍'
      }
    }
    if (!form.industryInvolved) {
      return {
        status: false,
        value: '行业获取失败，请重新获取'
      }
    }
    if (!form.site) {
      return {
        status: false,
        value: '地址获取失败，请重新获取'
      }
    }
    if (!form.businessLicense) {
      return {
        status: false,
        value: '请上传营业执照'
      }
    }
    if (!form.wxName) {
      return {
        status: false,
        value: '请输入真实姓名'
      }
    }
    var phoneReg = /^1[3-578]\d{9}$/;
    if (!form.wxPhone && !phoneReg.test(form.wxPhone)) {
      return {
        status: false,
        value: '请检查手机号'
      }
    }
    return {
      status: true,
      value: ''
    }
  },

  /**
   * 统一图片上传
   */
  uploadImg: function (e) {
    let type = e.currentTarget.dataset.type
    let num = e.currentTarget.dataset.num //1单张 2多张

    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: 'compressed',
      success: function (res) {
        wx.showLoading({
          title: '上传中',
        })
        wx.uploadFile({
          url: app.globalData.BASE_URL + '/wx/appletFeedback/uploadimg',
          header: {
            Authorization: 'wx' + wx.getStorageSync('Token')
          },
          filePath: res.tempFiles[0].path,
          name: 'file',
          formData: {
            'file': res.tempFiles[0].path
          },
          success(res) {
            const data = res.data
            console.log('成功上传', num, JSON.parse(data).data.url)
            if (num == 1) { //单张上传
              let itemName = 'form.' + type
              that.setData({
                [itemName]: JSON.parse(data).data.url
              })
              console.log(itemName, that.data.form)
            } else { //多张拼接
              let itemName = 'form.' + type
              if (type == 'honorCertification') { //荣誉照片
                if (that.data.honorCertificationArr.length >= 4) {
                  wx.showToast({
                    title: '最多上传4张',
                    icon: 'none'
                  })
                  return
                }
                let historyImg = that.data.form.honorCertification ? that.data.form.honorCertification + ',' : ''
                let honorCertificationStr = historyImg + JSON.parse(data).data.url
                that.setData({
                  [itemName]: honorCertificationStr,
                  honorCertificationArr: honorCertificationStr.split(',')
                })
                console.log(itemName, that.data.honorCertificationArr)

              }
            }
            setTimeout(() => {
              wx.hideLoading()
            }, 1000)
          },
          fail: function () {
            wx.hideLoading()
            wx.showToast({
              title: '上传失败，请稍后重试',
              icon: 'none'
            })
          }
        })
      }
    })
  },

  /**
   * 统一图片删除
   */
  deleteImg: function (e) {
    let that = this
    let type = e.currentTarget.dataset.type
    let num = e.currentTarget.dataset.num //1单张 >2多张

    if (num == 1) {
      let itemName = 'form.' + type
      that.setData({
        [itemName]: ''
      })
    } else {
      if (type == 'honorCertification') { //荣誉资质
        let index = e.currentTarget.id
        let honorCertificationArr = that.data.honorCertificationArr
        honorCertificationArr.splice(index, 1)
        let itemName = 'form.' + type
        that.setData({
          honorCertificationArr,
          [itemName]: honorCertificationArr.join(',')
        })
        console.log(honorCertificationArr.join(','), honorCertificationArr)
      }
    }
  },

  /**
   * 视频上传
   */
  uploadVideo: function (e) {
    console.log('上传文件')
    let that = this
    let type = e.currentTarget.dataset.type
    let num = e.currentTarget.dataset.num //1单张 2多张
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success(res) {
        wx.showLoading({
          title: '上传中',
        })
        wx.uploadFile({
          url: app.globalData.BASE_URL + '/common/uploadFile2Cos',
          header: {
            Authorization: 'wx' + wx.getStorageSync('token')
          },
          filePath: res.tempFilePath,
          name: 'file',
          formData: {
            'file': res.tempFilePath
          },
          success(res) {
            const data = res.data
            console.log('成功上传', num, JSON.parse(data).url)
            if (num == 1) { //单张上传
              let itemName = 'form.' + type
              that.setData({
                [itemName]: JSON.parse(data).url
              })
              console.log(itemName, that.data.form)
            } else {

            }
            setTimeout(() => {
              wx.hideLoading()
            }, 1000)
          },
          fail: function () {
            wx.hideLoading()
            wx.showToast({
              title: '上传失败，请稍后重试',
              icon: 'none'
            })
          }
        })
      }
    })
  },

  /**
   * 文件上传 - 获取微信对话的文件
   */
  uploadFile: function (e) {
    let that = this
    let type = e.currentTarget.dataset.type
    let num = e.currentTarget.dataset.num //1单张 2多张

    wx.chooseMessageFile({
      type: 'file',
      count: 1,
      extension: ['pdf'],
      success(res) {
        console.log(res.tempFiles[0].path)
        wx.uploadFile({
          url: app.globalData.BASE_URL + '/common/uploadFile2Cos',
          header: {
            Authorization: 'wx' + wx.getStorageSync('token')
          },
          filePath: res.tempFiles[0].path,
          name: 'file',
          formData: {
            'file': res.tempFiles[0].path
          },
          success(res) {
            const data = res.data
            console.log('成功上传', num, JSON.parse(data).url)
            if (num == 1) { //单张上传
              let itemName = 'form.' + type
              that.setData({
                [itemName]: JSON.parse(data).url
              })
              console.log(itemName, that.data.form)
            } else {

            }
            setTimeout(() => {
              wx.hideLoading()
            }, 1000)
          },
          fail: function () {
            wx.hideLoading()
            wx.showToast({
              title: '上传失败，请稍后重试',
              icon: 'none'
            })
          }
        })
      }
    })


    if (type == 'brochure') { //宣传手册

    }

  },

  /**
   * 职位选择改变
   */
  positionChange: function (e) {
    let that = this
    // console.log('职位',e.detail.value)
    this.setData({
      positionIndex: e.detail.value,
      ['form.post']: that.data.positionArr[that.data.positionIndex]
    })
  },
})